package com.nf.health.app.datamain.activity;

import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.android.volley.VolleyError;
import com.nf.health.app.R;
import com.nf.health.app.activity.global.BaseActivity;
import com.nf.health.app.activity.my.MyShopStoreActivity;
import com.nf.health.app.adapter.OnMyClickListener;
import com.nf.health.app.customview.MenuPopupWindow;
import com.nf.health.app.customview.MyBrokenLineView;
import com.nf.health.app.customview.WheelView;
import com.nf.health.app.http.RequestProvider;
import com.nf.health.app.models.DataDetailExtra;
import com.nf.health.app.models.DataDetails;
import com.nf.health.app.models.DeviceData;
import com.nf.health.app.service.BluetoothLeService;
import com.nf.health.app.utils.ActivityUtils;
import com.nf.health.app.utils.LogUtil;
import com.nf.health.app.utils.PreferenceHelper;
import com.nf.health.app.utils.Util;
import com.nf.health.app.utils.ViewUtil;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.bluetools.ProtocolParser;

public class BloodPressureActivity extends BaseActivity {

    private static final long INTERVAL_TIME = 5 * 1000;
    private static final String FLAG_BLOOD_PRESSURE = "flagBloodPressure";
    private static final String FLAG_ADD_DATA = "flagAddBloodPressure";
    private static final String FLAG_ADD_DATA_MANUALLY = "flag_add_data_manually";
    private static final String TAG = BloodPressureActivity.class.getSimpleName();
    @Bind(R.id.iv_type_icon)
    ImageView ivTypeIcon;
    @Bind(R.id.tv_type_value)
    TextView tvTypeValue;
    @Bind(R.id.tv_type_name)
    TextView tvTypeName;
    @Bind(R.id.tv_bluetooth)

    TextView tvBluetooth;
    @Bind(R.id.rg_bracelet_navigator)
    RadioGroup rgBraceletNavigator;
    @Bind(R.id.tv_tab_high)
    TextView tvTabHigh;
    @Bind(R.id.tv_tab_low)
    TextView tvTabLow;
    @Bind(R.id.tv_tab_heart)
    TextView tvTabHeart;
    @Bind(R.id.history_text)
    TextView historyText;
    @Bind(R.id.tv_unit)
    TextView tvUnit;
    @Bind(R.id.rl_broken_line)
    LinearLayout rlBrokenLine;
    @Bind(R.id.titlebar_right_view)
    ImageView titlebarRightView;
    @Bind(R.id.btn_start_measure)
    Button btnStartMeasure;
    String h = "0", d = "0", x = "0";
    @Bind(R.id.rb_high_pressure)
    RadioButton rbHighPressure;
    @Bind(R.id.hsrcol)
    HorizontalScrollView hsrcol;
    @Bind(R.id.sc_top)
    ScrollView sc_top;


    private int goal = 120;
    public static ArrayList<Float> yValue = new ArrayList<>();
    private ArrayList<String> xValues;
    private ArrayList<String> yValues;
    private List<DataDetails> dataDetails = new ArrayList<>();
    //为防止测量一次上传两次数据，我们加了一个标识去记录
    private boolean isFirstUpLoad = true;
    private boolean isFeedBack = false;//是否接收到血压计反馈
    private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
                tvBluetooth.setText("(已连接)");
            } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
                showToast("蓝牙连接断开,请重试");
                tvBluetooth.setText("(未连接)");
                hideLoading();
            } else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mBluetoothLeService.startUpTest();
                    }
                }, 500);

            } else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
                byte[] data = intent.getByteArrayExtra(BluetoothLeService.EXTRA_DATA);
                if (data == null) {
                    return;
                }
                LogUtil.e(TAG, "接收到数据" + ProtocolParser.binaryToHexString(data) + ">>>>" + data.length);
                try {
                    handleBloodPressureData(data);
                } catch (Exception e) {
                    LogUtil.exception(e);
                }
            }
        }
    };
    // Device scan callback.
    private BluetoothAdapter.LeScanCallback mLeScanCallback;
    private BluetoothAdapter mBluetoothAdapter;
    // 蓝牙服务类
    private BluetoothLeService mBluetoothLeService;
    private List<BluetoothDevice> devices = new ArrayList<>();

    private ServiceConnection mServiceConnection;
    /**
     * 标记TAB
     */
    private int currentIndex = 0;
    /**
     * 标记是否追加数据
     */
    private boolean isAppend = false;
    private byte[] result = new byte[24 * 3];
    /**
     * 复制字节数组的长度
     */
    int length = 0;

    int high, low, heart = 0;
    private String deviceType;
    private Handler mHandler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitleBar(R.layout.titlebar_base);
        setContent(R.layout.activity_blood_pressure);
        ButterKnife.bind(this);

        ViewUtil.setText(this, R.id.titlebar_title_tv, "血压数据");
        titlebarRightView.setImageResource(R.drawable.ic_title_setting);

        if (provider == null) {
            provider = new RequestProvider(this);
        }

        deviceType = getIntent().getStringExtra("deviceType");

        initListener();

        initBluetooth();
    }

    private void initData() {
        //线形图  group  实例化

        if (TextUtils.isEmpty(deviceType) || deviceType == null) {

        } else {
            provider.requestDataDetailsnew(deviceType, "1", "15", FLAG_BLOOD_PRESSURE);
        }

    }

    private void initBluetooth() {
        // 检查当前手机是否支持blue 蓝牙,如果不支持退出程序
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            showToast("不支持蓝牙4.0通讯");
            finish();
            return;
        }

        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        // 检查设备上是否支持蓝牙
        if (mBluetoothAdapter == null) {
            showToast("没有发现蓝牙模块");
            return;
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
                @Override
                public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (device != null) {
                                if (!TextUtils.isEmpty(device.getName())) {
                                    if (device.getName().toLowerCase().contains("module")) {
                                        if (!devices.contains(device)) {
                                            devices.add(device);
                                        }
                                    }
                                }
                            }
//                            if (device != null && device.getName().contains(BluetoothDeviceAttr.BLOOD_PRESSURE_DEVICE_NAME)) {
//                                if (!devices.contains(device)) {
//                                    devices.add(device);
//                                }
//                            }
                        }
                    });
                }
            };
        } else {
            showToast("设备蓝牙版本过低");
            finish();
            return;
        }
        bindLeService();
        if (!mBluetoothAdapter.isEnabled()) {
            mBluetoothAdapter.enable();
        }
    }

    private void bindLeService() {
        mServiceConnection = new ServiceConnection() {

            @Override
            public void onServiceConnected(ComponentName componentName,
                                           IBinder service) {
                mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
                if (!mBluetoothLeService.initialize()) {
                    new MaterialDialog.Builder(BloodPressureActivity.this)
                            .title("提示")
                            .content("蓝牙初始化服务失败了~")
                            .positiveText("确定")
                            .onPositive(new MaterialDialog.SingleButtonCallback() {
                                @Override
                                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                    finish();
                                }
                            })
                            .show();
                }
            }

            @Override
            public void onServiceDisconnected(ComponentName componentName) {
                mBluetoothLeService = null;
            }
        };

        Intent bleService = new Intent(this, BluetoothLeService.class);
        bleService.putExtra("type", DeviceData.Type.BLOOD_PRESSURE);
        bindService(bleService, mServiceConnection, Context.BIND_AUTO_CREATE);
    }

    private void initListener() {
        titlebarRightView.setOnClickListener(this);
        btnStartMeasure.setOnClickListener(this);
        rgBraceletNavigator.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                currentIndex = checkedId;
                resetTabValue();
            }
        });
        //历史数据
        historyText.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.titlebar_right_view:
                showPop();
                break;
            case R.id.btn_start_measure:
                //如果没有绑定设备，则先进行搜索
                if (PreferenceHelper.getBoolean(PreferenceHelper.BLOOD_PRESSUER_IS_BING, false)) {
                    showToast("测量准备就绪中....");
                    isFeedBack = false;
                    if (BluetoothLeService.isConnected) {
                        mBluetoothLeService.startUpTest();
                    } else {
                        mBluetoothLeService.connect(PreferenceHelper.getString(PreferenceHelper.BLOOD_PRESSUER_ADDRESS, ""));
                    }
                } else {
                    showPop();
                }
                break;
            case R.id.history_text:
                ActivityUtils.showActivity(this, BloodPressureHistoryDataActivity.class);
                break;
        }
    }

    @Override
    public void handleActionSuccess(String actionName, Object object) {
        if (FLAG_BLOOD_PRESSURE.equals(actionName)) {
            hideLoading();
            DataDetailExtra extra = (DataDetailExtra) object;
            List<DataDetails> tempList = extra.getDeviceData();
            if (tempList.size() != 0) {
                if (tempList.get(0).getxValue().size() == 0) {//防止没有数据时小康报错
                    showToast("暂无数据");
                    return;
                }
                dataDetails.clear();
                dataDetails.addAll(tempList);
//                refreshView(1);

                h = tempList.get(0).getyValue().get(tempList.get(0).getyValue().size() - 1);
                d = tempList.get(1).getyValue().get(tempList.get(1).getyValue().size() - 1);
                x = tempList.get(2).getyValue().get(tempList.get(2).getyValue().size() - 1);
                tvTabLow.setText(h);
                tvTabHigh.setText(d);
                tvTabHeart.setText(x);
                tvTabHigh.setTextColor(Color.parseColor("#FFF36A"));
                tvTabLow.setTextColor(Color.parseColor("#FFFFFF"));
                tvTabHeart.setTextColor(Color.parseColor("#FFFFFF"));
                tvTypeValue.setText(d + "mmHg");
                rbHighPressure.setChecked(true);
                refreshView(1);//高压
            }
        } else if (FLAG_ADD_DATA_MANUALLY.equals(actionName)) {
            showToast("手动添加,数据上传云端成功");
            provider.requestAddScore("11", "");//添加积分
            initData();
        } else if (FLAG_ADD_DATA.equals(actionName)) {
            hideLoading();
            showToast("数据已上传到云端");
            provider.requestAddScore("11", "");//添加积分
            isFeedBack = false;
            /**
             * 上传成功跳转到测量结果界面
             */
            ActivityUtils.showActivity(BloodPressureActivity.this, BloodPresureMeasuredResultActivity.class);
        }
    }

    @Override
    public void handleActionError(String actionName, String response, VolleyError error) {
        super.handleActionError(actionName, response, error);
        hideLoading();
        switch (actionName) {
            case FLAG_ADD_DATA:
                isFirstUpLoad = true;
                break;
        }
    }

    @Override
    public void handleActionStart(String actionName, Object object) {
        super.handleActionStart(actionName, object);
        switch (actionName) {
            case FLAG_BLOOD_PRESSURE:
                showLoading("加载中...");
                break;
        }
    }

    public void refreshView(int position) {
        if (dataDetails.size() <= 0) {
            return;
        }
        tvTabLow.setText(h);
        tvTabHigh.setText(d);
        tvTabHeart.setText(x);

        tvUnit.setText("单位:  " + dataDetails.get(position).getUnit());
        yValue.clear();
        xValues = dataDetails.get(position).getxValue();
        yValues = dataDetails.get(position).getyValue();
        ArrayList<String> y_array = dataDetails.get(position).getY_array();
        float max = Float.parseFloat(y_array.get(y_array.size() - 1));
        float min = Float.parseFloat(y_array.get(0));

        for (int i = 0; i < yValues.size(); i++) {
            if (!TextUtils.isEmpty(yValues.get(i))) {
                try {
                    yValue.add(Float.parseFloat(yValues.get(i)));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                yValue.add(Float.valueOf(0));
            }
        }
        rlBrokenLine.removeAllViews();
        //  rlBrokenLine.addView(new BrokenLineNewBlood(this, xValues, yValue, max, min, y_array.size(), goal));
        MyBrokenLineView view = null;
        view = new MyBrokenLineView(this, xValues, yValue);
        rlBrokenLine.addView(view);
        switch (position) {
            case 0://低压
                //view =  new MyBrokenLineView(this,xValues,yValue,60,80);
                view.setMyGoadToLine(60, 80);
                break;
            case 1://高压
                // view =  new MyBrokenLineView(this,xValues,yValue,80,120);
                view.setMyGoadToLine(80, 120);
                break;
            case 2://心率
                //  view =  new MyBrokenLineView(this,xValues,yValue,60);
                view.setGoal_one(60);
                break;
        }
        mHandler.post(mScrollToBottom);
    }

    private void showPop() {
        MenuPopupWindow pop = new MenuPopupWindow(this, PreferenceHelper.getString(PreferenceHelper.BLOOD_PRESSUER_NAME, ""));
        pop.showAsDropDown(titlebarRightView);
        pop.setOnMenuItemClickListener(new OnMyClickListener() {
            @Override
            public void onClick(int position, String flag) {
                if (R.id.ll_bind_device == position) {
                    if (PreferenceHelper.getBoolean(PreferenceHelper.BLOOD_PRESSUER_IS_BING, false)) {
                        //TODO 解绑操作
                        PreferenceHelper.putBoolean(PreferenceHelper.BLOOD_PRESSUER_IS_BING, false);
                        PreferenceHelper.putString(PreferenceHelper.BLOOD_PRESSUER_ADDRESS, "");
                        PreferenceHelper.putString(PreferenceHelper.BLOOD_PRESSUER_NAME, "");
                        showToast("解绑成功");
                        mBluetoothLeService.close();
                        tvBluetooth.setText("(未连接)");
                    } else {
                        scanLeDevice(true);
                    }
                } else if (R.id.tv_manual_input == position) {
                    //TODO 手动输入
                    manuallyAddDada();
                } else if (R.id.tv_loadl_input == position) {
                    ActivityUtils.showActivity(BloodPressureActivity.this, MyShopStoreActivity.class);
                }
            }
        });
    }

    /**
     * 高压 低压 心率 范围&所选值
     */
    private String[] high_pressure_range = new String[160];
    private String[] low_pressure_range = new String[80];
    private String[] heart_rate_range = new String[80];
    private String high_pressure_chosen = "120";
    private String low_pressure_chosen = "80";
    private String heart_rate_chosen = "70";

    private void manuallyAddDada() {
        for (int i = 0; i < 160; i++) {
            high_pressure_range[i] = i + 80 + "";
            if (i < 80) {
                low_pressure_range[i] = i + 40 + "";
                heart_rate_range[i] = i + 30 + "";
            }
        }
        high_pressure_chosen = "120"; //默认120
        low_pressure_chosen = "80";   //默认80
        heart_rate_chosen = "70";     //默认70

        View outerView = LayoutInflater.from(this).inflate(R.layout.wheel_view_blood_pressure, null);
        WheelView wv_high = (WheelView) outerView.findViewById(R.id.wheel_view_high_pressure);
        WheelView wv_low = (WheelView) outerView.findViewById(R.id.wheel_view_low_pressure);
        WheelView wv_heart = (WheelView) outerView.findViewById(R.id.wheel_view_heart_rate);

        wv_high.setOffset(1);
        wv_high.setItems(Arrays.asList(high_pressure_range));
        wv_high.setSeletion(40);
        wv_high.setOnWheelViewListener(new WheelView.OnWheelViewListener() {
            @Override
            public void onSelected(int selectedIndex, String item) {
                high_pressure_chosen = item;
            }
        });

        wv_low.setOffset(1);
        wv_low.setItems(Arrays.asList(low_pressure_range));
        wv_low.setSeletion(low_pressure_range.length / 2);
        wv_low.setOnWheelViewListener(new WheelView.OnWheelViewListener() {
            @Override
            public void onSelected(int selectedIndex, String item) {
                low_pressure_chosen = item;
            }
        });

        wv_heart.setOffset(1);
        wv_heart.setItems(Arrays.asList(heart_rate_range));
        wv_heart.setSeletion(heart_rate_range.length / 2);
        wv_heart.setOnWheelViewListener(new WheelView.OnWheelViewListener() {
            @Override
            public void onSelected(int selectedIndex, String item) {
                heart_rate_chosen = item;
            }
        });

        new AlertDialog.Builder(this)
                .setTitle("请选择")
                .setView(outerView)
                .setNegativeButton("取消", null)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        System.out.println(high_pressure_chosen + " " + low_pressure_chosen + " " + heart_rate_chosen);
                        //上传选择的数据
                        provider.requestAddDeviceBlood(Integer.valueOf(high_pressure_chosen), Integer.valueOf(low_pressure_chosen), Integer.valueOf(heart_rate_chosen), "1", FLAG_ADD_DATA_MANUALLY);
                        tvTabHigh.setText(high_pressure_chosen + "");
                        tvTabLow.setText(low_pressure_chosen + "");
                        tvTabHeart.setText(heart_rate_chosen + "");

                        h = low_pressure_chosen;
                        d = high_pressure_chosen;
                        x = heart_rate_chosen;

                    }
                })
                .show();
    }

    private void scanLeDevice(final boolean enable) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            if (enable) {
                showLoading("查找设备中..");
                devices.clear();
                mBluetoothAdapter.stopLeScan(mLeScanCallback);
                // Stops scanning after a pre-defined scan period.
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
                            mBluetoothAdapter.stopLeScan(mLeScanCallback);
                            hideLoading();
                            showBluetoothNames();
                        }
                    }
                }, INTERVAL_TIME);
                mBluetoothAdapter.startLeScan(mLeScanCallback);
            } else {
                try {
                    mBluetoothAdapter.stopLeScan(mLeScanCallback);
                } catch (Exception e) {
                }
            }
        }
    }

    /**
     * FE810000000001FF  开机
     * FE820000000002FF  关机
     * FE83              测量错误
     * FE84              袖带压力
     * FE85              电池没电
     * FF010100000001000C  结果输出3次
     *
     * @param data
     */
    private void handleBloodPressureData(byte[] data) {
        if (isAppend && isFeedBack) {
            System.arraycopy(data, 0, result, length, data.length);
            length += data.length;
            if (data[data.length - 1] == (byte) 0xFE) {
                hideLoading();
                //TODO
                high = result[10] & 0xFF;
                low = result[11] & 0xFF;
                heart = result[12] & 0xFF;

                resetTabValue();

                isAppend = false;
                /**
                 * 测量结果拼接成字符串存储到sp
                 */
                String result = high + "," + low + "," + heart;
                PreferenceHelper.putString(PreferenceHelper.BLOOD_PRESSURE_MEASURED_INFO, result);
                if (isFirstUpLoad) {
                    isFirstUpLoad = false;
                    uploadBloodPressure("2");
                }

            }
        } else {
            if (data[0] == (byte) 0xFE && data.length > 1) {
                switch (data[1]) {
                    case (byte) 0x81:
                        showLoading("测量中...");
                        //延时设置反馈标记,避免下个命令是ff的结尾
                        mHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                isFeedBack = true;
                            }
                        }, 2000);
                        break;
                    case (byte) 0x82:
                        break;
                    case (byte) 0x83:
                        hideLoading();
                        switch (data[2]) {
                            case 0x01:// 测量过程中没有侦测到脉搏信号
                            case 0x02:// 测量错误，测量过长中干扰过大
                            case 0x05:// 测量失败，测量的结果高压与低压相差太大
                                showToast("测量失败");
                                break;
                            case 0x03:// 充气失败，充气时间过长或袖带漏气
                                showToast("充气失败");
                                break;
                            default:
                                break;
                        }
                        break;
                    case (byte) 0x84:
                        break;
                    case (byte) 0x85:
                        hideLoading();
                        break;
                    default:
                        break;
                }
            } else if (data[0] == (byte) 0xFF && isFeedBack) {//ff开头可能是测量结果,也可能是新版血压计第一次上电连接后的返回,还有可能是开始测量的包尾
                isAppend = true;
                LogUtil.e(TAG, "追加数据");
                System.arraycopy(data, 0, result, 0, data.length);
                length = data.length;
            }
        }
    }

    /**
     * @param type 1手动录入 2,恩福产品 3其他产品
     */
    private synchronized void uploadBloodPressure(String type) {
        provider.requestAddDeviceBlood(high, low, heart, type, FLAG_ADD_DATA);
    }

    private void resetTabValue() {
        switch (currentIndex) {
            case R.id.rb_high_pressure:

                tvTabHigh.setTextColor(Color.parseColor("#FFF36A"));
                tvTabLow.setTextColor(Color.parseColor("#FFFFFF"));
                tvTabHeart.setTextColor(Color.parseColor("#FFFFFF"));
                goal = 120;
                tvTypeName.setText("高压");
                ivTypeIcon.setImageResource(R.drawable.ic_high_pressure);
                if (high == 0) {
                    tvTypeValue.setText(d + "mmHg");
                } else {
                    tvTypeValue.setText(high + "mmHg");
                }
                refreshView(1);//高压
                break;
            case R.id.rb_low_pressure:
                tvTabHigh.setTextColor(Color.parseColor("#FFFFFF"));
                tvTabLow.setTextColor(Color.parseColor("#FFF36A"));
                tvTabHeart.setTextColor(Color.parseColor("#FFFFFF"));
                tvTypeName.setText("低压");
                goal = 80;
                ivTypeIcon.setImageResource(R.drawable.ic_low_pressure);
                if (low == 0) {
                    tvTypeValue.setText(h + "mmHg");
                } else {
                    tvTypeValue.setText(low + "mmHg");
                }
                refreshView(0);//低压
                break;
            case R.id.rb_heart_rate:
                tvTabHigh.setTextColor(Color.parseColor("#FFFFFF"));
                tvTabLow.setTextColor(Color.parseColor("#FFFFFF"));
                tvTabHeart.setTextColor(Color.parseColor("#FFF36A"));
                tvTypeName.setText("心跳K");
                goal = 60;
                ivTypeIcon.setImageResource(R.drawable.ic_heart_rate);
                if (heart == 0) {
                    tvTypeValue.setText(x + "次");
                } else {
                    tvTypeValue.setText(heart + "次");
                }
                refreshView(2);//心率
                break;
        }
        tvTabHigh.setText(d + "");
        tvTabLow.setText(h + "");
        tvTabHeart.setText(x + "");
    }

    private void showBluetoothNames() {
        if (devices.size() <= 0) {
            // new MaterialDialog.Builder(this).title("提示").content("没有发现血压计噢~").positiveText("确定").show();
            Util.showNotHasFountDeviced(BloodPressureActivity.this);
            return;
        }
        String[] deviceNames = new String[devices.size()];
        for (int i = 0; i < devices.size(); i++) {
            String address = devices.get(i).getAddress();
            deviceNames[i] = "血压计-" + address.replace(":", "");
        }
        //mLeScanCallback 将搜索结果添加到集合中
        if (!isFinishing()) {
            new MaterialDialog.Builder(this)
                    .title("血压计")
                    .items(deviceNames)
                    .itemsCallback(new MaterialDialog.ListCallback() {
                        @Override
                        public void onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
//                        mBluetoothLeService.connect(devices.get(which).getAddress());
                            PreferenceHelper.putBoolean(PreferenceHelper.BLOOD_PRESSUER_IS_BING, true);
                            PreferenceHelper.putString(PreferenceHelper.BLOOD_PRESSUER_NAME, "血压计-" + devices.get(which).getAddress().replace(":", ""));
                            PreferenceHelper.putString(PreferenceHelper.BLOOD_PRESSUER_ADDRESS, devices.get(which).getAddress());
                            dialog.dismiss();
                        }
                    })
                    .show();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(mGattUpdateReceiver, BluetoothLeService.makeGattUpdateIntentFilter());
        isFirstUpLoad = true;
        initData();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mGattUpdateReceiver != null) {
            unregisterReceiver(mGattUpdateReceiver);
        }
        isFirstUpLoad = false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mServiceConnection != null) {
            unbindService(mServiceConnection);
        }
        mBluetoothLeService.close();
        mBluetoothLeService = null;
        mHandler.removeCallbacksAndMessages(null);
    }

    @Override
    protected void onUserLeaveHint() {
        super.onUserLeaveHint();
    }

    private Runnable mScrollToBottom = new Runnable() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            int off = rlBrokenLine.getMeasuredWidth() - hsrcol.getWidth();
            if (off > 0) {
                hsrcol.scrollTo(off, 0);
            }
        }
    };

}
